package com.hzit.mmcb.core.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzit.common.exception.Assert;
import com.hzit.common.result.PageResult;
import com.hzit.common.result.ResponseEnum;
import com.hzit.common.utils.MD5;
import com.hzit.mmb.base.utils.JwtUtils;
import com.hzit.mmcb.core.pojo.dto.UserInfoDTO;
import com.hzit.mmcb.core.pojo.entity.UserAccount;
import com.hzit.mmcb.core.pojo.entity.UserInfo;
import com.hzit.mmcb.core.mapper.UserInfoMapper;
import com.hzit.mmcb.core.pojo.entity.UserLoginRecord;
import com.hzit.mmcb.core.pojo.vo.RegisterVO;
import com.hzit.mmcb.core.pojo.vo.UserIndexVO;
import com.hzit.mmcb.core.pojo.vo.UserLoginVO;
import com.hzit.mmcb.core.pojo.vo.UserSearchVO;
import com.hzit.mmcb.core.service.UserAccountService;
import com.hzit.mmcb.core.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzit.mmcb.core.service.UserLoginRecordService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.nio.file.Watchable;
import java.util.List;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author ljh
 * @since 2024-08-27
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private UserLoginRecordService userLoginRecordService;


    /**
     * 注册
     * @param registerVO
     */
    @Override
    public void register(RegisterVO registerVO) {
        //判断信息格式是否正确
        //判断号码不能为空
        Assert.notNull(registerVO.getMobile(), ResponseEnum.MOBILE_NULL_ERROR);
        //判断密码不能为空
        Assert.notNull(registerVO.getPassword(),ResponseEnum.PASSWORD_NULL_ERROR);
        //验证码不能为空
        Assert.notNull(registerVO.getCode(),ResponseEnum.CODE_NULL_ERROR);
        //判断电话号码是否被注册
        int count = this.count(new QueryWrapper<UserInfo>().eq("mobile", registerVO.getMobile()));
        Assert.isTrue(count==0,ResponseEnum.MOBILE_EXIST_ERROR);
        //判断验证码的正确性
        String s = stringRedisTemplate.opsForValue().get("service-sms" + registerVO.getMobile());
        Assert.equals(registerVO.getCode(),s,ResponseEnum.CODE_ERROR);
        //注册信息
        UserInfo userInfo=new UserInfo();
        userInfo.setMobile(registerVO.getMobile());
        userInfo.setPassword(MD5.encrypt(registerVO.getPassword()));
        userInfo.setUserType(registerVO.getUserType());

        this.save(userInfo);


        //填写用户账户
        UserAccount userAccount=new UserAccount();
        userAccount.setUserId(userInfo.getId());
        userAccountService.save(userAccount);
    }

    /**
     * 登录
     * @param userLoginVO
     * @param ip
     * @return
     */

    @Override
    public UserInfoDTO login(UserLoginVO userLoginVO, String ip) {
        String mobile = userLoginVO.getMobile();
        String password = userLoginVO.getPassword();
        Integer userType = userLoginVO.getUserType();

        //判断信息是否正确
        Assert.notNull(mobile,ResponseEnum.MOBILE_ERROR);
        Assert.notNull(password,ResponseEnum.PASSWORD_NULL_ERROR);
        UserInfo user = this.getOne(new QueryWrapper<UserInfo>()
                .eq("mobile", mobile)
                .eq("user_type", userType));
        Assert.notNull(user,ResponseEnum.MOBILE_ERROR);
        Assert.equals(MD5.encrypt(password),user.getPassword(),ResponseEnum.LOGIN_PASSWORD_ERROR);
        Assert.isTrue(user.getStatus()==1,ResponseEnum.LOGIN_LOKED_ERROR);
        //生成token
        String token = JwtUtils.createToken(user.getId(), user.getName());
        UserInfoDTO userInfoDTO=new UserInfoDTO();
        BeanUtils.copyProperties(user,userInfoDTO);
        userInfoDTO.setToken(token);
        //填写登录日志
        UserLoginRecord record=new UserLoginRecord();
        record.setUserId(user.getId());
        record.setIp(ip);
        userLoginRecordService.save(record);
        return userInfoDTO;
    }


    /**
     * 后台管理系统查询会员
     * @param page
     * @param pageSize
     * @param userSearch
     * @return
     */
    @Override
    public PageResult<UserInfo> listPage(Integer page, Integer pageSize, UserSearchVO userSearch) {
        QueryWrapper<UserInfo>  queryWrapper=new QueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(userSearch.getMobile()),"mobile",userSearch.getMobile())
                .eq(userSearch.getStatus()!=null,"status",userSearch.getStatus())
                .eq(userSearch.getUserType()!=null,"user_type",userSearch.getUserType());

        Page<UserInfo> page1 = this.page(new Page<>(page, pageSize), queryWrapper);

        return new PageResult<>(page1.getTotal(),page1.getRecords());
    }

    /**
     * 修改用户状态
     * @param id
     * @param status
     */

    @Override
    public void lock(Long id, Integer status) {
        UserInfo userInfo=new UserInfo();
        userInfo.setId(id);
        userInfo.setStatus(status);
        this.updateById(userInfo);
    }

    @Override
    public boolean checkMobile(String mobile) {
        UserInfo user = this.getOne(new QueryWrapper<UserInfo>().eq("mobile", mobile));

        return user==null?false:true;
    }

    @Override
    public UserIndexVO getIndexUserInfo(Long userId) {
        //用户信息
        UserInfo userInfo = this.getById(userId);
        //用户账户信息
        UserAccount userAccount = userAccountService.getOne(new LambdaQueryWrapper<UserAccount>().eq(UserAccount::getUserId, userId));
        //用户登录信息
        UserLoginRecord userLoginRecord = userLoginRecordService.getOne(new LambdaQueryWrapper<UserLoginRecord>().eq(UserLoginRecord::getUserId, userId).orderByDesc(UserLoginRecord::getId)
                .last("limit 1"));
        //组装vo
        UserIndexVO userIndexVO = new UserIndexVO();
        userIndexVO.setUserId(userInfo.getId());
        userIndexVO.setUserType(userInfo.getUserType());
        userIndexVO.setName(userInfo.getName());
        userIndexVO.setNickName(userInfo.getNickName());
        userIndexVO.setHeadImg(userInfo.getHeadImg());
        userIndexVO.setBindStatus(userInfo.getBindStatus());
        userIndexVO.setAmount(userAccount.getAmount());
        userIndexVO.setFreezeAmount(userAccount.getFreezeAmount());
        userIndexVO.setLastLoginTime(userLoginRecord.getCreateTime());

        return userIndexVO;
    }


}
